<?php

class ForumController extends BaseController {
        
    public $isForumModerator = false;
    public $moderPost = false;

    public function actions() {
        return array(
            'upload'=>array(
                'class'=>'application.actions.XImgUploadAction',
                'path' =>Yii::app()->getBasePath() . "/../images/uploads/comments",
                'publicPath' => Yii::app() -> getBaseUrl() . "/images/uploads/comments",
                'secureFileNames'=>true,
                'subfolderVar' => false,
                'imagesTable'=>'forum_images',
            ),
        );
    }
    
    public function init() {
        if(!Yii::app()->request->isAjaxRequest && !isset($_POST['ForumTheme']) && !isset($_POST['ForumComments'])) Yii::app()->user->setState('xuploadFiles', array());
        Yii::app()->bootstrap->registerCoreCss();
        Yii::app()->bootstrap->registerYiiCss();
        Yii::app()->bootstrap->registerCoreScripts();
    }
    
    private function checkIsForumModerator($partnerId, $catId) {
        if(!Yii::app()->user->isGuest) {
            $user = Yii::app()->user->getAllUserInfo();
            if(Yii::app()->user->checkAccess('admin') || $user['moderForum']) $this->isForumModerator = true;
            else if(Yii::app()->user->checkAccess('moder')) {
                $res = Yii::app()->db->createCommand()->select('id')->from('forum_moderator')->where('userId='.Yii::app()->user->getId().' and catId='.$catId.' and (partnerId=0 or partnerId='.$partnerId.')')->queryRow();
                if(!empty($res)) $this->isForumModerator = true;
            }
            if($user['moderPost']) $this->moderPost = true;
        }
    }
        
    public function actionIndex($partnerUrl, $catId) {
        $cat = Yii::app()->db->createCommand()->select('catId, name')->from('partners_cat')->where("catId=$catId")->queryRow();
        if(empty($cat)) throw new CHttpException(404, 'Не найдено указанной записи');
        $partner = Yii::app()->db->createCommand()->select('partnerid, url, about, name, type, delegate1, delegate2')->from('partners')->where("url=\"$partnerUrl\" and catId=$catId")->queryRow();
        if(empty($partner)) throw new CHttpException(404, 'Не найдено указанной записи');
        $this->checkIsForumModerator($partner['partnerid'], $catId);
        $themeModel = new ForumTheme();
        if(isset($_POST['ForumTheme'])) {
            if($themeModel->save())
                $this->redirect(Yii::app()->createUrl('partner/forum/theme', array('catId'=>$cat['catId'], 'partnerUrl'=>$partner['url'], 'url'=>$themeModel['url'])));
            else Yii::app()->user->setState('xuploadFiles', array());
        } 
        $commentModel = new ForumComments();
        if(isset($_POST['ForumComments'])) {
            if($commentModel->save()) {
                $themeUrl = Yii::app()->db->createCommand()->select('url')->from('forum_theme')->where('themeId='.$commentModel->themeId)->queryRow();
                $this->redirect(Yii::app()->createUrl('partner/forum/theme', array('catId'=>$cat['catId'], 'partnerUrl'=>$partner['url'], 'url'=>$themeUrl['url'])));
            } else Yii::app()->user->setState('xuploadFiles', array());
        }
        $errorModel = new ErrorReporting();
        if(isset($_POST['ErrorReporting'])) {
            if($errorModel->save()) $this->refresh();
        }
        $subCats = Yii::app()->db->createCommand()->select('c.name, c.catId, c.parentId, rc.partnerId')->from('partners_sub_cat_rel rc')->join('partners_cat c', 'c.catId=rc.catId')->where('partnerid='.$partner['partnerid'])->queryAll();
        $relProfiles = Yii::app()->db->createCommand()->select('*')->from('partners_relprofiles')->where("partnerid=".$partner['partnerid'])->queryAll();
        if(!Yii::app()->user->isGuest) $userIsWork = Yii::app()->db->createCommand()->select('id')->from('partners_users')->where('userId='.Yii::app()->user->getId().' and partnerId='.$partner['partnerid'])->queryRow();
        $this->brending('partner', $partner['partnerid'], $cat['catId']);
        $pagination = new CPagination(ForumTheme::model()->count('`partnerId`='.$partner['partnerid']));
        $pagination->setPageSize(10);
        $themes = Yii::app()->db->createCommand()->select('t.title, t.themeId, t.isSupport, t.url, t.countComments, c.*')->from('forum_theme t')->join('forum_comments c', 'c.themeId = t.themeId and c.isFirst=1')->where('partnerId='.$partner['partnerid'])->order('date DESC')->limit($pagination->getLimit())->offset($pagination->getOffset())->queryAll();
        if(!empty($themes)) {
            $sql = '';
            $userIdArr = $idArr = array();
            for ($i=0; $i<count($themes); $i++) {
                $idArr[] = $themes[$i]['comId'];
                $userIdArr[] = $themes[$i]['userId'];
                if($i) $sql .= ' UNION ';
                $sql .= '('.Yii::app()->db->createCommand()->select('c.*')->from('forum_comments c')->where('themeId='.$themes[$i]['themeId'].' and isFirst=0')->limit('3')->order('comDate desc')->text.')';
            }
            $sql .= ';';
            $themeImg = Yii::app()->db->createCommand()->select('*')->from('forum_images')->where(array('in', 'comId', $idArr))->queryAll();
            $comments = Yii::app()->db->createCommand($sql)->query()->readAll();
            $sql = 
            'SELECT 
                u.login, u.displayName, u.role, u.userid,
                count(DISTINCT r.revId) AS reviews, 
                count(DISTINCT nc.comId) AS newsComments, 
                count(DISTINCT fc.comId) AS forumComments, 
                count(DISTINCT rc.comId) AS revComments, 
                count(DISTINCT bc.id) AS blogComments
            FROM `users` `u`
                LEFT JOIN `reviews_comments` `rc` ON rc.userid = u.userid
                LEFT JOIN `news_comments` `nc` ON nc.userid = u.userid
                LEFT JOIN `forum_comments` `fc` ON fc.userid = u.userid
                LEFT JOIN `reviews` `r` ON r.userid = u.userid
                LEFT JOIN `blog_comments` `bc` ON bc.userid = u.userid
            WHERE u.userid IN('.implode(',', $userIdArr).') GROUP BY u.userId';
            $themeUsers = Yii::app()->db->createCommand($sql)->query()->readAll();
            for ($i=0; $i<count($themes); $i++) {
                foreach ($themeImg as $k=>$v) {
                    if($v['comId'] == $themes[$i]['comId']) {
                        $themes[$i]['images'][] = $v;
                        unset($themeImg[$k]);
                    }
                }
                for($j=0; $j<count($themeUsers); $j++) {
                    if($themeUsers[$j]['userid'] == $themes[$i]['userId']) {
                        $themes[$i]['role'] = $themeUsers[$j]['role'];
                        $themes[$i]['login'] = $themeUsers[$j]['login'];
                        $themes[$i]['displayName'] = $themeUsers[$j]['displayName'];
                        $themes[$i]['count'] = $themeUsers[$j]['reviews']+$themeUsers[$j]['newsComments']+$themeUsers[$j]['forumComments']+$themeUsers[$j]['revComments']+$themeUsers[$j]['blogComments'];
                    }
                }
            }
            if(!empty($comments)) {
                $idArr = array();
                foreach($comments as $item) {$idArr[] = $item['comId']; $userIdArr[] = $item['userId'];}
                $images = Yii::app()->db->createCommand()->select('*')->from('forum_images')->where(array('in', 'comId', $idArr))->queryAll();
                #$comUsers = Yii::app()->db->createCommand()->select('login, displayName, userid, avatar, role')->from('users')->where(array('in', 'userid', $userIdArr))->queryAll();
                $sql = 
                'SELECT 
                    u.userid, u.login, u.displayName, u.avatar, u.role,
                    count(DISTINCT r.revId) AS reviews, 
                    count(DISTINCT nc.comId) AS newsComments, 
                    count(DISTINCT fc.comId) AS forumComments, 
                    count(DISTINCT rc.comId) AS revComments, 
                    count(DISTINCT bc.id) AS blogComments
                FROM `users` `u`
                    LEFT JOIN `reviews_comments` `rc` ON rc.userid = u.userid
                    LEFT JOIN `news_comments` `nc` ON nc.userid = u.userid
                    LEFT JOIN `forum_comments` `fc` ON fc.userid = u.userid
                    LEFT JOIN `reviews` `r` ON r.userid = u.userid
                    LEFT JOIN `blog_comments` `bc` ON bc.userid = u.userid
                WHERE u.userid IN('.implode(',', $userIdArr).') GROUP BY u.userId';
                $comUsers = Yii::app()->db->createCommand($sql)->query()->readAll();
                
                for($i=0; $i<count($themes); $i++) {
                    for($j=0; $j<count($comments); $j++) {
                        if(!empty($images)) {
                            foreach($images as $k=>$v) {
                                if($v['comId'] == $comments[$j]['comId']) {
                                    $comments[$j]['images'][] = $v;
                                    unset($images[$k]);
                                }
                            }
                        }
                        if(!empty($comUsers)) {
                            foreach ($comUsers as $k=>$v) {
                                if($v['userid'] == $comments[$j]['userId']) $comments[$j]['user'] = $v;
                            }
                        }
                        if($themes[$i]['themeId'] == $comments[$j]['themeId']) $themes[$i]['comments'][] = $comments[$j];
                    }
                }
            }
        }
        if(!Yii::app()->user->isGuest) {
            if(!empty($themes)) {
                $idArr = array();
                foreach ($themes as $t) $idArr[] = $t['themeId'];
                $isUserSign = Yii::app()->db->createCommand()->select('typeId')->from('subscribers')->where('`type`="forum_topic" and `userId`='.Yii::app()->user->getId().' and `typeId` IN('.implode(',', $idArr).')')->queryAll();
            }
        }
        $advertCode = Yii::app()->db->createCommand()->select('b.code')->from('banners_relations r')->join('banners b', 'b.bannerId=r.bannerId and b.type="Спонсор категории на главной" ')->where('r.catId='.$catId)->queryScalar();
        $this->render('index', array('partner'=>$partner, 'advertCode'=>$advertCode, 'isUserSign'=>!empty($isUserSign) ? $isUserSign : '', 'errorModel'=>$errorModel, 'relProfiles'=>$relProfiles, 'subCats'=>$subCats, 'cat'=>$cat, 'themes'=>$themes, 'pagination'=>$pagination, 'themeModel'=>$themeModel, 'commentModel'=>$commentModel, 'userIsWork'=>!empty($userIsWork) ? $userIsWork : ''));
    }
    
    public function actionTheme($url, $partnerUrl, $catId) {
        $cat = Yii::app()->db->createCommand()->select('catId, name')->from('partners_cat')->where("catId=$catId")->queryRow();
        if(empty($cat)) throw new CHttpException(404, 'Не найдено указанной записи');
        $partner = Yii::app()->db->createCommand()->select('partnerid, url, about, name, type, delegate1, delegate2')->from('partners')->where("url=\"$partnerUrl\" and catId=$catId")->queryRow();
        if(empty($partner)) throw new CHttpException(404, 'Не найдено указанной записи');
        $themeModel = new ForumTheme();
        if(isset($_POST['ForumTheme'])) {
            if($themeModel->save()) {
                $this->redirect(Yii::app()->createUrl('partner/forum/theme', array('catId'=>$cat['catId'], 'partnerUrl'=>$partner['url'], 'url'=>$themeModel['url'])));
            } else Yii::app()->user->setState('xuploadFiles', array());
        }
        $commentModel = new ForumComments();
        if(isset($_POST['ForumComments'])) {
            if($commentModel->save()) {
                $this->refresh();
            } else Yii::app()->user->setState('xuploadFiles', array());
        } 
        $errorModel = new ErrorReporting();
        if(isset($_POST['ErrorReporting'])) {
            if($errorModel->save()) $this->refresh();
        } 
        $this->checkIsForumModerator($partner['partnerid'], $catId);
        $this->brending('partner', $partner['partnerid'], $cat['catId']);
        $subCats = Yii::app()->db->createCommand()->select('c.name, c.catId, c.parentId, rc.partnerId')->from('partners_sub_cat_rel rc')->join('partners_cat c', 'c.catId=rc.catId')->where('partnerid='.$partner['partnerid'])->queryAll();
        $relProfiles = Yii::app()->db->createCommand()->select('*')->from('partners_relprofiles')->where("partnerid=".$partner['partnerid'])->queryAll();
        $theme = Yii::app()->db->createCommand()->select('t.title, t.themeId, t.isSupport, t.countComments, c.*')->from('forum_theme t')->join('forum_comments c', 'c.themeId = t.themeId and c.isFirst=1')->where('t.partnerId='.$partner['partnerid'].' and t.url="'.$url.'"')->queryRow();
        if(empty($theme)) throw new CHttpException(404, 'Не найдено указанной записи');
        $sql = 
        'SELECT 
            u.login, u.displayName, u.role,
            count(DISTINCT r.revId) AS reviews, 
            count(DISTINCT nc.comId) AS newsComments, 
            count(DISTINCT fc.comId) AS forumComments, 
            count(DISTINCT rc.comId) AS revComments, 
            count(DISTINCT bc.id) AS blogComments
        FROM `users` `u`
            LEFT JOIN `reviews_comments` `rc` ON rc.userid = u.userid
            LEFT JOIN `news_comments` `nc` ON nc.userid = u.userid
            LEFT JOIN `forum_comments` `fc` ON fc.userid = u.userid
            LEFT JOIN `reviews` `r` ON r.userid = u.userid
            LEFT JOIN `blog_comments` `bc` ON bc.userid = u.userid
        WHERE u.userid='.$theme['userId'].' GROUP BY u.userId';
        $theme['user'] = Yii::app()->db->createCommand($sql)->query()->read();
        $themeImg = Yii::app()->db->createCommand()->select('*')->from('forum_images')->where('comId='.$theme['comId'])->queryAll();
        $count = Yii::app()->db->createCommand()->select('count(*) as count')->from('forum_comments')->where('themeId='.$theme['themeId'].' and isFirst=0')->queryRow();
        $pagination = new CPagination($count['count']);
        $pagination->setPageSize(10);
        $comments = Yii::app()->db->createCommand()->select('c.text, c.comDate, c.userIp, c.userId, c.comId')->from('forum_comments c')->where('`themeId`='.$theme['themeId'].' and `isFirst`=0')->limit($pagination->getLimit())->offset($pagination->getOffset())->queryAll();
        if(!empty($comments)) {
            $idArr = $userIdArr = array();
            for($i=0; $i<count($comments); $i++) {
                $userIdArr[] = $comments[$i]['userId'];
                $idArr[] = $comments[$i]['comId'];
            }
            $sql = 
            'SELECT 
                u.login, u.displayName, u.role, u.userid,
                count(DISTINCT r.revId) AS reviews, 
                count(DISTINCT nc.comId) AS newsComments, 
                count(DISTINCT fc.comId) AS forumComments, 
                count(DISTINCT rc.comId) AS revComments, 
                count(DISTINCT bc.id) AS blogComments
            FROM `users` `u`
                LEFT JOIN `reviews_comments` `rc` ON rc.userid = u.userid
                LEFT JOIN `news_comments` `nc` ON nc.userid = u.userid
                LEFT JOIN `forum_comments` `fc` ON fc.userid = u.userid
                LEFT JOIN `reviews` `r` ON r.userid = u.userid
                LEFT JOIN `blog_comments` `bc` ON bc.userid = u.userid
            WHERE u.userid IN('.implode(',', $userIdArr).') GROUP BY u.userId';
            $comUsers = Yii::app()->db->createCommand($sql)->query()->readAll();
            $images = Yii::app()->db->createCommand()->select('*')->from('forum_images')->where(array('in', 'comId', $idArr))->queryAll();
            for($i=0; $i<count($comments); $i++) {
                $comments[$i]['user'] = $comments[$i]['images'] = array();
                for($l=0; $l<count($images); $l++) {
                    if($images[$l]['comId'] == $comments[$i]['comId']) 
                        $comments[$i]['images'][] = $images[$l];
                }
                for($j=0; $j<count($comUsers); $j++) {
                    if($comments[$i]['userId'] == $comUsers[$j]['userid']) 
                        $comments[$i]['user'] = $comUsers[$j];
                }
            }
        }
        if(!Yii::app()->user->isGuest) {
            $visit = Yii::app()->db->createCommand()->select('id')->from('user_visits')->where('type="forum" and typeId='.$theme['themeId'].' and userId='.Yii::app()->user->getId())->queryRow();
            if(!empty($visit))
                Yii::app()->db->createCommand()->update('user_visits', array('visitDate'=>time()), 'type="forum" and typeId='.$theme['themeId'].' and userId='.Yii::app()->user->getId());
            else Yii::app()->db->createCommand()->insert('user_visits', array('visitDate'=>time(), 'type'=>'forum', 'typeId'=>$theme['themeId'], 'userId'=>Yii::app()->user->getId()));
            $userIsWork = Yii::app()->db->createCommand()->select('id')->from('partners_users')->where('userId='.Yii::app()->user->getId().' and partnerId='.$partner['partnerid'])->queryRow();
            $isUserSign = Yii::app()->db->createCommand('select 1 from `subscribers` where `type`="forum_topic" and `typeid`='.$theme['themeId'].'  and `userId`='.Yii::app()->user->getId().' limit 1')->query()->read();
        }
        $advertCode = Yii::app()->db->createCommand()->select('b.code')->from('banners_relations r')->join('banners b', 'b.bannerId=r.bannerId and b.type="Спонсор категории на главной" ')->where('r.catId='.$catId)->queryScalar();
        $this->render('theme', array('theme'=>$theme, 'advertCode'=>$advertCode, 'isUserSign'=>!empty($isUserSign) ? true : false, 'errorModel'=>$errorModel, 'themeImg'=>$themeImg, 'cat'=>$cat, 'pagination'=>$pagination, 'commentModel'=>$commentModel, 'themeModel'=>$themeModel, 'partner'=>$partner, 'comments'=>$comments, 'userIsWork'=>!empty($userIsWork) ? $userIsWork : '', 'relProfiles'=>$relProfiles, 'subCats'=>$subCats));
    }
    
    public function actionEditComment($id) {
        $errorModel = new ErrorReporting();
        if(isset($_POST['ErrorReporting'])) {
            if($errorModel->save()) $this->refresh();
        }
        $model = ForumComments::model()->findByPk($id);
        if(!$model) throw new CHttpException(404, 'Не найдено указанной записи');
        if(isset($_POST['ForumComments'])) {
            if($model->save()) 
                $this->redirect(Yii::app()->session->get('return-url', $_SERVER['HTTP_REFERER']));
        } else Yii::app()->session->add('return-url', isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : Yii::app()->baseUrl);
        if($model->userId) $user = Yii::app()->db->createCommand()->select('login, displayName, avatar, userid')->from('users')->where('`userid`='.$model->userId)->queryRow();
        $partner = Yii::app()->db->createCommand()->select('t.partnerId, p.url, p.about, p.name, p.type, p.delegate1, p.delegate2, p.partnerid, c.catId')->from('forum_theme t')->join('partners p', 'p.partnerid=t.partnerId')->join('partners_cat c', 'c.catId=p.catId')->where('`themeId`='.$model->themeId)->queryRow();
        $cat = Yii::app()->db->createCommand()->select('catId, name')->from('partners_cat')->where("catId=".$partner['catId'])->queryRow();
        $this->checkIsForumModerator($partner['partnerid'], $cat['catId']);
        if(!$this->isForumModerator && !$this->moderPost) throw new CHttpException(404);
        $this->brending('partner', $partner['partnerid'], $cat['catId']);
        $subCats = Yii::app()->db->createCommand()->select('c.name, c.catId, c.parentId, rc.partnerId')->from('partners_sub_cat_rel rc')->join('partners_cat c', 'c.catId=rc.catId')->where('partnerid='.$partner['partnerid'])->queryAll();
        $relProfiles = Yii::app()->db->createCommand()->select('*')->from('partners_relprofiles')->where("partnerid=".$partner['partnerId'])->queryAll();
        
        if(!Yii::app()->user->isGuest) $userIsWork = Yii::app()->db->createCommand()->select('id')->from('partners_users')->where('userId='.Yii::app()->user->getId().' and partnerId='.$partner['partnerId'])->queryRow();
        $images = Yii::app()->db->createCommand()->select('*')->from('forum_images')->where('`comId`='.$id)->queryAll();
        $advertCode = Yii::app()->db->createCommand()->select('b.code')->from('banners_relations r')->join('banners b', 'b.bannerId=r.bannerId and b.type="Спонсор категории на главной" ')->where('r.catId='.$cat['catId'])->queryScalar();
        $this->render('editComment', array('model'=>$model, 'advertCode'=>$advertCode, 'errorModel'=>$errorModel, 'cat'=>$cat, 'images'=>$images, 'user'=>!empty($user) ? $user : '', 'userIsWork'=>$userIsWork, 'relProfiles'=>$relProfiles, 'partner'=>$partner, 'subCats'=>$subCats));
    }
    
    public function actionEditTheme($id) {
        $errorModel = new ErrorReporting();
        if(isset($_POST['ErrorReporting'])) {
            if($errorModel->save()) $this->refresh();
        }
        $model = ForumTheme::model()->findByPk($id);
        if(!$model) throw new CHttpException(404, 'Не найдено указанной записи');
        if(isset($_POST['ForumTheme'])) {
            if($model->save()) 
                $this->redirect(Yii::app()->session->get('return-url', $_SERVER['HTTP_REFERER']));
        } else Yii::app()->session->add('return-url', isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : Yii::app()->baseUrl);
        if($model->userId) $user = Yii::app()->db->createCommand()->select('login, avatar, userid')->from('users')->where('`userid`='.$model->userId)->queryRow();
        $partner = Yii::app()->db->createCommand()->select('p.partnerid, p.url, p.about, p.name, p.type, p.delegate1, p.delegate2, c.catId')->from('partners p')->join('partners_cat c', 'c.catId=p.catId')->where("partnerid=".$model->partnerId)->queryRow();
        $cat = Yii::app()->db->createCommand()->select('catId, name')->from('partners_cat')->where("catId=".$partner['catId'])->queryRow();
        $this->checkIsForumModerator($partner['partnerid'], $cat['catId']);
        if(!$this->isForumModerator) throw new CHttpException(404);
        $this->brending('partner', $partner['partnerid'], $cat['catId']);
        
        $subCats = Yii::app()->db->createCommand()->select('c.name, c.catId, c.parentId, rc.partnerId')->from('partners_sub_cat_rel rc')->join('partners_cat c', 'c.catId=rc.catId')->where('partnerid='.$partner['partnerid'])->queryAll();
        $relProfiles = Yii::app()->db->createCommand()->select('*')->from('partners_relprofiles')->where("partnerid=".$partner['partnerid'])->queryAll();
        
        $com = Yii::app()->db->createCommand()->select('c.comId, c.text, c.comDate, u.login, u.displayName, u.avatar')->from('forum_comments c')->leftJoin('users u', 'u.userid=c.userId')->where('`c`.`themeId`='.$id.' and `isFirst`=1')->queryRow();
        $images = Yii::app()->db->createCommand()->select('*')->from('forum_images')->where('comId='.$com['comId'])->queryAll();
        if(!Yii::app()->user->isGuest) $userIsWork = Yii::app()->db->createCommand()->select('id')->from('partners_users')->where('userId='.Yii::app()->user->getId().' and partnerId='.$partner['partnerid'])->queryRow();
        $advertCode = Yii::app()->db->createCommand()->select('b.code')->from('banners_relations r')->join('banners b', 'b.bannerId=r.bannerId and b.type="Спонсор категории на главной" ')->where('r.catId='.$cat['catId'])->queryScalar();
        $this->render('editTheme', array('model'=>$model, 'advertCode'=>$advertCode, 'cat'=>$cat, 'errorModel'=>$errorModel, 'images'=>$images, 'com'=>$com, 'relProfiles'=>$relProfiles, 'subCats'=>$subCats, 'partner'=>$partner, 'userIsWork'=>$userIsWork));
    }
    
    public function actionLastForumMessages() {
        $count = Yii::app()->db->createCommand()->select('count(*) as count')->from('forum_comments')->where('isFirst=0')->queryRow();
        $pagination = new CPagination($count['count'] > 100 ? 100 : $count['count']);
        $pagination->setPageSize(10);
        $lastComments = Yii::app()->db->createCommand()->select('c.themeId, c.comId, c.comDate, ft.date, ft.url, ft.countComments, ft.title, p.url as partnerUrl, p.name, p.partnerId, p.catId, pc.name as catName, uft.login as uftlogin, uft.displayName')->from('forum_comments c')->join('forum_theme ft', 'ft.themeId=c.themeId')->join('forum_comments fc', 'fc.themeId=ft.themeId and fc.isFirst=1')->leftJoin('users uft', 'uft.userid=fc.userId')->join('partners p', 'p.partnerid=ft.partnerId')->join('partners_cat pc', 'pc.catId=p.catId')->where('c.isFirst=0')->order('c.comDate desc')->limit($pagination->getLimit())->offset($pagination->getOffset())->queryAll();
//        HPr::pr($lastComments);
        if(!empty($lastComments)) {
            $partnerId = array();
            for($i=0; $i<count($lastComments); $i++) $partnerId[] = $lastComments[$i]['partnerId'];
            $subCats = Yii::app()->db->createCommand()->select('c.name, c.catId, c.parentId, rc.partnerId')->from('partners_sub_cat_rel rc')->join('partners_cat c', 'c.catId=rc.catId')->where(array('in', 'partnerId', $partnerId))->queryAll();
            for($l=0; $l<count($subCats); $l++) {
                for($j=0; $j<count($lastComments); $j++) {
                    if($subCats[$l]['partnerId'] == $lastComments[$j]['partnerId']) 
                        $lastComments[$j]['subcats'][] = $subCats[$l]; 
                }
            }
            $themesId = array();
            $sql = '';
            for ($i=0; $i<count($lastComments); $i++) {
                if(!in_array($lastComments[$i]['themeId'], $themesId)) $themesId[] = $lastComments[$i]['themeId'];
                if($i) $sql .= ' UNION ';
                $sql .= '('.Yii::app()->db->createCommand()->select('c.*, u.login, u.displayName')->from('forum_comments c')->leftJoin('users u', 'u.userid=c.userId')->where('themeId='.$lastComments[$i]['themeId'].' and isFirst=0 and (comDate<='.$lastComments[$i]['comDate'].')' )->limit('3')->order('comId desc')->text.')';
            };
            $sql .= ';';
            $comments = Yii::app()->db->createCommand($sql)->query()->readAll();
            if(!empty($comments)) {
                for($i=0; $i<count($comments); $i++) {
                    for($l=0; $l<count($lastComments); $l++) {
                        if($comments[$i]['comId'] == $lastComments[$l]['comId']) {
                            $lastComments[$l]['comments'][] = $comments[$i];
                            if(!empty($comments[$i+1])) $lastComments[$l]['comments'][] = $comments[$i+1];
                            if(!empty($comments[$i+2])) $lastComments[$l]['comments'][] = $comments[$i+2];   
                        }
                    }    
                }            
            }
            if(!Yii::app()->user->isGuest) {
                $userVisits = Yii::app()->db->createCommand()->select('*')->from('user_visits')->where('type="forum" and userId='.Yii::app()->user->getId().' and typeId IN('.implode(',', $themesId).')')->queryAll();
                if(!empty($userVisits)) {
                    $sql = '';
                    $tmpAr = array();
                    for($i=0; $i<count($lastComments); $i++) {
                        for($j=0; $j<count($userVisits); $j++) {
                            if($userVisits[$j]['typeId'] == $lastComments[$i]['themeId'] && !in_array($userVisits[$j]['typeId'], $tmpAr)) {
                                if($sql) $sql .= ' UNION ';
                                $sql .= '(select count(comId), '.$userVisits[$j]['typeId'].' from forum_comments where themeId='.$userVisits[$j]['typeId'].' and isFirst=0 and comDate>='.$userVisits[$j]['visitDate'].')';
                                $tmpAr[] = $userVisits[$j]['typeId'];
                            }       
                        }
                    };
                    $sql .= ';';
                    $lastVisits = Yii::app()->db->createCommand($sql)->query()->readAll();
                    if(!empty($lastVisits)) {
                        for($i=0; $i<count($lastComments); $i++) {
                            for($l=0; $l<count($lastVisits); $l++) {
                                $id = '';
                                foreach ($lastVisits[$l] as $k=>$v) if($k != 'count(comId)') $id=$v;
                                if($id == $lastComments[$i]['themeId'])
                                    $lastComments[$i]['newCom'] = $lastVisits[$l]['count(comId)'];
                            }
                        }
                    }
                }    
            }
        }
        $this->render('lastForumMessages', array('pagination'=>$pagination, 'lastComments'=>$lastComments));
    }
}